<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FavipController extends Controller
{

    /**
     * 用户VIP列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['a.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['a.me_uid','like',"%{$param['me_uid']}%"];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['a.me_phone','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_nick_name']) && !empty($param['me_nick_name'])) {
            $whehe[] = ['a.me_nick_name','like',"%{$param['me_nick_name']}%"];
        }
        if (isset($param['fmember_id']) && !empty($param['fmember_id'])) {
            $whehe[] = ['b.member_id','=',$param['fmember_id']];
        }
        if (isset($param['fme_uid']) && !empty($param['fme_uid'])) {
            $whehe[] = ['b.me_uid','like',"%{$param['fme_uid']}%"];
        }
        if (isset($param['fme_phone']) && !empty($param['fme_phone'])) {
            $whehe[] = ['b.me_phone','like',"%{$param['fme_phone']}%"];
        }
        if (isset($param['fme_nick_name']) && !empty($param['fme_nick_name'])) {
            $whehe[] = ['b.me_nick_name','like',"%{$param['fme_nick_name']}%"];
        }
        if (isset($param['me_is_vip']) && $param['me_is_vip'] != '') {
            switch($param['me_is_vip']){
                case '1': $whehe[] = ['a.me_is_vip','=',1];$whehe[] = ['c.admin_id','=',0];break;//自行开通
                case '2': $whehe[] = ['a.me_is_vip','=',1];$whehe[] = ['c.admin_id','neq',0];break;//后台开通
                case '0': $whehe[] = ['a.me_is_vip','=',$param['me_is_vip']];break;//未开通
            }
        }
        if (isset($param['me_sex']) && !empty($param['me_sex'])) {
            $whehe[] = ['a.me_sex','=',$param['me_sex']];
        }

//        $whehe[] = ['a.me_is_vip','=',1];
        $IndexTableModel = New IndexTableModel();
        $data = Db::table('fa_member')
            ->alias('a')
            ->join("fa_member b",'a.me_parent = b.member_id',"LEFT")//父级
            ->join("fa_recharge_vip_order c",'a.member_id = c.member_id',"LEFT")//父级
            ->field("a.*,b.member_id as f_member_id,b.me_uid as f_me_uid,b.me_nick_name as f_me_nick_name,c.id as vip_order_id,c.admin_id as vip_admin_id,c.is_song,c.add_time as k_add_time")
            ->order('a.member_id desc')
            ->where($whehe)
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
        $adminid = $this->uid;
        $data->each(function ($v, $k)use($IndexTableModel,$adminid) {
            $v['k_add_time'] = empty($v['k_add_time'])?'-':date('Y-m-d H:i:s',$v['k_add_time']);

            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }
            if(empty($v['f_member_id'])){
                $v['me_parent_word'] = '未绑定';$v['me_bind_type_word'] = '未绑定';
            }else{
                $v['me_parent_word'] = $v['f_member_id'].'('.$v['f_me_uid'].')('.$v['f_me_nick_name'].')';
                if($v['me_bind_type'] == 1){
                    $v['me_bind_type_word'] = '扫码绑定';
                }else{
                    $v['me_bind_type_word'] = '充值绑定';
                }
            }
            switch($v['me_sex']){
                case '0': $v['me_sex_word'] = '未设置';break;
                case '1': $v['me_sex_word'] = '男';break;
                case '2': $v['me_sex_word'] = '女';break;
            }
            switch($v['me_is_vip']){
                case '0': $v['me_is_vip_word'] = '未开通';break;
                case '1': $v['me_is_vip_word'] = '已开通';break;
            }

            $v['is_button'] = '2';//是否展示 打开 或 关闭 VIP 按钮  1展示  2不展示
            if($v['me_is_vip'] == 1){
                $v['vip_order_word'] = '油票开通';
                if(empty($v['vip_admin_id'])){
                    $v['is_button'] = '1';
                }
                if($v['vip_admin_id'] == 9999){
                    $v['vip_order_word'] = '体验开通';
                    $v['is_button'] = '1';
                }
                if(!empty($v['vip_admin_id']) && $v['vip_admin_id'] != 9999){
                    $v['vip_order_word'] = '后台开通';
                    $v['is_button'] = '1';
                }
            }else{
                $v['vip_order_word'] = '未开通';
                $v['is_button'] = '1';
            }

            $v['is_song_word'] = '-';
            if(empty($v['vip_order_id'])){
                $v['is_song_word'] = '-';
            }else{
                if(!empty($v['is_song'])){
                    $v['is_song_word'] = '赠送人ID'.$v['is_song'];
                }
                if(empty($v['vip_admin_id']) && empty($v['is_song'])){
                    $v['is_song_word'] = '自费';
                }
            }

            $v['me_status_time_word'] = '-';
            switch($v['me_status']){
                case '1': $v['me_status_word'] = '正常';$v['me_status_time_word'] = '未封禁';break;
                case '2': $v['me_status_word'] = '封禁';
                    if($v['me_status_time'] != -1 && $v['me_status_time'] != 0){
                        $v['me_status_time_word'] = date('Y-m-d H:i:s',$v['me_status_time']);
                    }else{
                        $v['me_status_time_word'] = '永久';
                    }
                    break;
            }

            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
                $v['me_status'] = 99;
                $v['me_status_time_word'] = '已注销';
            }
            $v['me_add_time'] = date('m-d H:i',$v['me_add_time']);
            $v['me_bind_time_word'] = !empty($v['me_bind_time'])?date('m-d H:i',$v['me_bind_time']):'未绑定';
            return $v;
        });

        //自行开通VIP人数
        $zxktvip = Db::table('fa_member')
            ->alias('a')
            ->join("fa_recharge_vip_order c",'a.member_id = c.member_id',"LEFT")//父级
            ->where("a.me_is_vip = 1 and c.admin_id = 0")->count('a.member_id');
        //后台开通VIP人数
        $htktvip = Db::table('fa_member')
            ->alias('a')
            ->join("fa_recharge_vip_order c",'a.member_id = c.member_id',"LEFT")//父级
            ->where("a.me_is_vip = 1 and c.admin_id != 0")->count('a.member_id');
        //未开通VIP人数
        $wkktvip = Db::table('fa_member')
            ->where("me_is_vip = 0")->count('member_id');

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'zxktvip' => $zxktvip,
            'htktvip' => $htktvip,
            'wkktvip' => $wkktvip,
        ]);
        return $this->fetch();
    }


    /**
     * 打开VIP
     * User:@hang
     */
    public function openvip($id){
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:openvip'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'*');
        if($memberInfo['me_standing_type'] == 2){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在上级，并且是充值绑定，不可为用户开通VIP',URL_CLOSE_REFRESH);
        }
        if($memberInfo['me_is_vip'] == 1){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经开通VIP',URL_CLOSE_REFRESH);
        }
        if($memberInfo['me_zhuxiao'] == 1){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经注销，不可为其开通VIP',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        $Common = New Common();
        $pay_stamp = $Common->getConfigValue('vipmoney');//开通VIP需要支付油票数
        $viptime = $Common->getConfigValue('viptime');//VIP有效时间（天）
        //计算用户vip到期时间
        if($memberInfo['me_vip_overtime'] == 0){
            $me_vip_overtime = bcadd($ctime,bcmul($viptime,86400,0),0);
        }else{
            $me_vip_overtime = bcadd($memberInfo['me_vip_overtime'],bcmul($viptime,86400,0),0);
        }
        Db::startTrans();
        //添加用户充值VIP订单表
        $orderData = array();
        $orderData['member_id'] = $id;
        $orderData['fid'] = $memberInfo['me_parent'];
        $orderData['order_number'] = 'VIPADMIN'.$id.$ctime.rand(10,99).rand(100,999);
        $orderData['pay_money'] = $pay_stamp;
        $orderData['add_time'] = $ctime;
        $orderData['end_time'] = $me_vip_overtime;
        $orderData['ip'] = getIP();
        $orderData['admin_id'] = $this->uid;
        $orderId = $IndexTableModel->addInfo('fa_recharge_vip_order',$orderData);
        if(empty($orderId)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('生成VIP开通订单失败',URL_CLOSE_REFRESH);
        }
        $memberRes = $IndexTableModel->editInfo('fa_member',array('member_id'=>$id),array('me_is_vip'=>1,'me_vip_overtime'=>$me_vip_overtime));
        if(empty($memberRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改用户信息失败',URL_CLOSE_REFRESH);
        }
        //增加服务通知
        $newRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>6,'member_id'=>$id,'j_member_id'=>$id,'g_table'=>'fa_recharge_vip_order','g_id'=>$orderId,'content'=>'系统于 '.date('Y年m月d日 H:i:s',$ctime).' 为您成功开通VIP，VIP权益永久有效。','is_read'=>0,'add_time'=>$ctime));
        if(empty($newRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加服务通知失败',URL_CLOSE_REFRESH);
        }

        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 6;
        $data['member_id'] = $id;
        $data['d_member_id'] = $id;
        $data['content'] = '为【'.$memberInfo['member_id'].'】用户直接开通VIP';
        $data['add_time'] = time();
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit(); // 提交事务
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('为用户直接开通VIP成功', URL_RELOAD);
    }


    /**
     * 关闭VIP
     * User:@hang
     */
    public function shutvip($id){
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:shutvip'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'*');
        if($memberInfo['me_standing_type'] == 2){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在上级，并且是充值绑定，不可为用户关闭VIP',URL_CLOSE_REFRESH);
        }
        if($memberInfo['me_is_vip'] != 1){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户还未开通VIP',URL_CLOSE_REFRESH);
        }
        $vipOrderInfo = $IndexTableModel->getFind('fa_recharge_vip_order',"`member_id` = '{$id}'",'*');
        if($vipOrderInfo['admin_id'] == 0){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户自行开通的VIP，不可关闭',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        //删除用户充值VIP订单表
        $orderRes = $IndexTableModel->delOne('fa_recharge_vip_order',"`id` = '{$vipOrderInfo['id']}'");
        if(empty($orderRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('删除VIP开通订单失败',URL_CLOSE_REFRESH);
        }
        $memberRes = $IndexTableModel->editInfo('fa_member',array('member_id'=>$id),array('me_is_vip'=>0,'me_vip_overtime'=>0));
        if(empty($memberRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改用户信息失败',URL_CLOSE_REFRESH);
        }
        //增加服务通知
        $newRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>6,'member_id'=>$id,'j_member_id'=>$id,'g_table'=>'fa_recharge_vip_order','g_id'=>$vipOrderInfo['id'],'content'=>'抱歉，系统于 '.date('Y年m月d日 H:i:s',$ctime).' 将您VIP权益关闭。','is_read'=>0,'add_time'=>$ctime));
        if(empty($newRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加服务通知失败',URL_CLOSE_REFRESH);
        }
        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 7;
        $data['member_id'] = $id;
        $data['d_member_id'] = $id;
        $data['content'] = '将【'.$memberInfo['member_id'].'】用户VIP关闭';
        $data['add_time'] = time();
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit(); // 提交事务
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('为用户关闭VIP成功', URL_RELOAD);
    }





}
